<script setup>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";

const { locale } = useI18n();

defineProps({
  msg: String,
});

onMounted(async () => {
  changeLangText();
});

const langText = ref("");
const enText = "Switch to English";
const zhText = "切换为中文";

const getAssetsFile = (url) => {
  return new URL(`/public/img/${url}.png`, import.meta.url).href;
};

const switchLang = () => {
  if (langText.value === enText) {
    locale.value = "en";
    // localStorage.setItem("lang", "en");
    sessionStorage.setItem("lang", "en");
  } else {
    locale.value = "zh";
    // localStorage.setItem("lang", "zh");
    sessionStorage.setItem("lang", "zh");
  }
  changeLangText();
  // location.reload();
};
const changeLangText = () => {
  // const lang = localStorage.getItem("lang");
  const lang = sessionStorage.getItem("lang");
  langText.value = !lang || lang === "zh" ? enText : zhText;
};
</script>

<template>
  <div class="langSwitch" @click="switchLang">
    <img class="icon" :src="getAssetsFile('lang')" alt="" />
    <div class="text">{{ langText }}</div>
  </div>
</template>

<style lang="less" scoped>
.langSwitch {
  color: #fff;
  display: flex;
  align-items: center;
  cursor: pointer;
  .icon {
    width: 20px;
    margin-right: 5px;
  }
  .text {
    font-size: 16px;
  }
}
</style>
